package com.share.common.utils;

import java.math.BigDecimal;

/**
 * 输入参数为空,则计算结果为空
 */
public class DecimalUtil {

    /**
     * 返回值: fenzi/fenmu
     *
     * @param fenzi
     * @param fenmu
     * @return
     */
    public static Double divide(Double fenzi, Double fenmu) {
        return divide(fenzi, fenmu, 2, BigDecimal.ROUND_HALF_UP);
    }

    public static Double divide(Double fenzi, Double fenmu, int ditNum) {
        return divide(fenzi, fenmu, ditNum, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 返回值: (end -start)/start
     *
     * @param start
     * @param end
     * @return
     */
    public static Double growthRatio(Double start, Double end) {
        return divide(subtract(end, start), start, 2, BigDecimal.ROUND_HALF_UP);
    }

    public static Double growthRatio(Double start, Double end, int dotNum) {
        return divide(subtract(end, start), start, dotNum, BigDecimal.ROUND_HALF_UP);
    }

    //是否为0
    public static boolean isZero(Double value) {
        if (value == null) {
            return false;
        } else {
            return BigDecimal.ZERO.compareTo(new BigDecimal(value)) == 0;
        }
    }

    //减法
    public static Double subtract(Double left, Double right) {
        if (left == null || right == null) {
            return null;
        }

        BigDecimal subtract = new BigDecimal(left).subtract(new BigDecimal(right));
        return subtract.doubleValue();
    }

    //除法
    private static Double divide(Double fenzi, Double fenmu, int dotNum, int roundingMode) {
        if (fenzi == null || fenmu == null) {
            return null;
        }

        BigDecimal _z = new BigDecimal(fenzi);
        if (isZero(fenmu)) {
            return null;
        }

        BigDecimal _m = new BigDecimal(fenmu);
        BigDecimal divide = _z.divide(_m, dotNum, roundingMode);
        return divide.doubleValue();
    }
}
